<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智能AI终端</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #1e1e1e;
            color: #d4d4d4;
            height: 100vh;
            display: flex;
            flex-direction: column;
        }
        
        .header {
            background-color: #252526;
            color: #cccccc;
            padding: 10px 15px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 1px solid #3c3c3c;
        }
        
        .header h1 {
            font-size: 1.2rem;
            font-weight: 400;
        }
        
        .status-bar {
            background-color: #007acc;
            color: white;
            padding: 3px 10px;
            font-size: 0.8rem;
        }
        
        .container {
            display: flex;
            flex: 1;
            height: calc(100vh - 60px);
        }
        
        
        .terminal-area {
            flex: 1;
            display: flex;
            flex-direction: column;
            background-color: #1e1e1e;
        }
        
        .terminal-header {
            background-color: #2d2d30;
            padding: 8px 15px;
            border-bottom: 1px solid #3c3c3c;
            font-size: 0.9rem;
            display: flex;
            justify-content: space-between;
        }
        
        .terminal-tabs {
            display: flex;
        }
        
        .terminal-tab {
            padding: 5px 15px;
            background-color: #252526;
            border-right: 1px solid #3c3c3c;
            cursor: pointer;
        }
        
        .terminal-tab.active {
            background-color: #1e1e1e;
        }
        
        .terminal-content {
            flex: 1;
            padding: 15px;
            font-family: 'Courier New', monospace;
            font-size: 14px;
            line-height: 1.4;
            overflow-y: auto;
            white-space: pre-wrap;
        }
        
        .command-line {
            color: #d4d4d4;
        }
        
        .command-output {
            color: #9cdcfe;
            margin: 5px 0 15px 0;
        }
        
        .command-error {
            color: #f48771;
        }
        
        .command-success {
            color: #b5cea8;
        }
        
        .command-info {
            color: #569cd6;
        }
        
        .ai-suggestion {
            background-color: rgba(86, 156, 214, 0.1);
            border-left: 2px solid #569cd6;
            padding: 10px;
            margin: 10px 0;
            font-size: 0.9rem;
        }
        
        .smart-input-area {
            background-color: #252526;
            padding: 10px 15px;
            border-top: 1px solid #3c3c3c;
        }
        
        .command-input-container {
            position: relative;
        }
        
        .prompt {
            color: #569cd6;
            margin-right: 8px;
        }
        
        .command-input {
            width: calc(100% - 25px);
            background-color: transparent;
            color: #d4d4d4;
            border: none;
            font-family: 'Courier New', monospace;
            font-size: 14px;
            outline: none;
            caret-color: #d4d4d4;
        }
        
        .command-suggestions {
            position: absolute;
            bottom: 100%;
            left: 0;
            right: 0;
            background-color: #252526;
            border: 1px solid #3c3c3c;
            border-bottom: none;
            max-height: 150px;
            overflow-y: auto;
            z-index: 100;
            display: none; /* 默认隐藏 */
        }
        
        .suggestion-item {
            padding: 8px 15px;
            color: #d4d4d4;
            cursor: pointer;
            border-bottom: 1px solid #3c3c3c;
            font-family: 'Courier New', monospace;
            font-size: 14px;
        }
        
        .suggestion-item:hover, .suggestion-item.active {
            background-color: #007acc;
        }
        
        .suggestion-confidence {
            float: right;
            color: #b5cea8;
            font-size: 0.9em;
        }
        
        
        /* 上下文建议区域样式 */
        .context-suggestions {
            background-color: rgba(86, 156, 214, 0.05);
            border: 1px solid rgba(86, 156, 214, 0.2);
            border-radius: 6px;
            margin: 15px 0;
            font-size: 0.9rem;
        }

        .suggestions-header {
            background-color: rgba(86, 156, 214, 0.1);
            padding: 10px 15px;
            border-bottom: 1px solid rgba(86, 156, 214, 0.2);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .toggle-suggestions {
            background-color: #569cd6;
            color: white;
            border: none;
            border-radius: 3px;
            width: 24px;
            height: 24px;
            cursor: pointer;
            font-size: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .toggle-suggestions:hover {
            background-color: #4a8bc2;
        }

        .suggestions-content.collapsed {
            display: none;
        }

        .suggestions-title {
            font-weight: 500;
            color: #569cd6;
        }

        .suggestions-info {
            font-size: 0.8rem;
            color: #888888;
        }

        .suggestions-content {
            padding: 15px;
        }

        .command-sequence {
            margin-bottom: 15px;
        }

        .sequence-item {
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 4px 0;
            font-family: 'Courier New', monospace;
            font-size: 0.85rem;
        }

        .sequence-item.current {
            background-color: rgba(86, 156, 214, 0.1);
            padding: 4px 8px;
            border-radius: 3px;
        }

        .sequence-number {
            width: 20px;
            height: 20px;
            background-color: #3c3c3c;
            color: #d4d4d4;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 0.75rem;
            flex-shrink: 0;
        }

        .sequence-item.current .sequence-number {
            background-color: #569cd6;
            color: white;
        }

        .sequence-command {
            flex: 1;
            color: #9cdcfe;
        }

        .sequence-result {
            color: #b5cea8;
            font-weight: bold;
        }

        .next-suggestions {
            border-top: 1px solid rgba(86, 156, 214, 0.2);
            padding-top: 15px;
        }

        .suggestion-title {
            margin-bottom: 10px;
            font-weight: 500;
        }

        .suggestion-items {
            display: flex;
            flex-direction: column;
            gap: 8px;
        }

        .suggestion-item {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 10px 12px;
            background-color: rgba(45, 45, 48, 0.5);
            border: 1px solid #3c3c3c;
            border-radius: 4px;
            transition: all 0.2s ease;
        }

        .suggestion-item.clickable {
            cursor: pointer;
        }

        .suggestion-item.clickable:hover {
            background-color: rgba(86, 156, 214, 0.1);
            border-color: #569cd6;
            transform: translateX(2px);
        }

        .suggestion-icon {
            font-size: 16px;
            flex-shrink: 0;
        }

        .suggestion-content {
            flex: 1;
        }

        .suggestion-cmd {
            font-family: 'Courier New', monospace;
            color: #9cdcfe;
            font-weight: 500;
            margin-bottom: 2px;
        }

        .suggestion-reason {
            font-size: 0.8rem;
            color: #888888;
        }

        .suggestion-confidence {
            font-size: 0.8rem;
            color: #b5cea8;
            font-weight: 500;
            min-width: 35px;
            text-align: right;
        }
        
        /* 功能按钮样式 */
        .toolbar {
            background-color: #2d2d30;
            padding: 12px 20px;
            border-top: 1px solid #3c3c3c;
            box-shadow: 0 -2px 8px rgba(0,0,0,0.3);
        }
        
        .toolbar-buttons {
            display: flex;
            gap: 16px;
            align-items: center;
            justify-content: center;
        }
        
        .toolbar-group {
            position: relative;
            display: inline-block;
        }
        
        .toolbar-button {
            background: linear-gradient(135deg, #404040 0%, #383838 100%);
            color: #e0e0e0;
            border: 1px solid #555;
            padding: 10px 16px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 0.85rem;
            font-weight: 500;
            display: flex;
            align-items: center;
            gap: 8px;
            min-width: 80px;
            justify-content: center;
            transition: all 0.2s ease;
            box-shadow: 0 2px 4px rgba(0,0,0,0.2);
        }
        
        .toolbar-button:hover {
            background: linear-gradient(135deg, #4a4a4a 0%, #424242 100%);
            transform: translateY(-1px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.3);
        }
        
        .toolbar-button.primary-button {
            background: linear-gradient(135deg, #0078d4 0%, #106ebe 100%);
            border-color: #005a9e;
            color: white;
        }
        
        .toolbar-button.primary-button:hover {
            background: linear-gradient(135deg, #106ebe 0%, #005a9e 100%);
        }
        
        .toolbar-button.ai-button {
            background: linear-gradient(135deg, #6c5ce7 0%, #5f3dc4 100%);
            border-color: #5f3dc4;
            color: white;
        }
        
        .toolbar-button.ai-button:hover {
            background: linear-gradient(135deg, #5f3dc4 0%, #4c3d99 100%);
        }
        
        .toolbar-button.files-button {
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
            border-color: #28a745;
            color: white;
        }
        
        .toolbar-button.files-button:hover {
            background: linear-gradient(135deg, #20c997 0%, #1e7e34 100%);
        }
        
        .button-icon {
            font-size: 1.1rem;
        }
        
        .button-text {
            font-weight: 500;
        }
        
        .dropdown-arrow {
            font-size: 0.7rem;
            margin-left: 4px;
            transition: transform 0.2s ease;
        }
        
        .toolbar-group:hover .dropdown-arrow {
            transform: rotate(180deg);
        }
        
        .ai-status-indicator {
            color: #27ae60;
            font-size: 0.6rem;
            margin-left: 4px;
            filter: drop-shadow(0 0 2px currentColor);
            animation: pulse 2s infinite;
        }
        
        @keyframes pulse {
            0%, 50%, 100% { opacity: 1; }
            25%, 75% { opacity: 0.7; }
        }
        
        .dropdown-menu {
            position: absolute;
            top: calc(100% + 8px);
            left: 0;
            background: #2d2d30;
            border: 1px solid #555;
            border-radius: 6px;
            box-shadow: 0 8px 24px rgba(0,0,0,0.4);
            z-index: 1000;
            min-width: 160px;
            overflow: hidden;
        }
        
        .dropdown-item {
            padding: 10px 16px;
            cursor: pointer;
            color: #d4d4d4;
            display: flex;
            align-items: center;
            gap: 8px;
            border-bottom: 1px solid #3c3c3c;
            transition: background-color 0.15s ease;
        }
        
        .dropdown-item:last-child {
            border-bottom: none;
        }
        
        .dropdown-item:hover {
            background-color: #007acc;
            color: white;
        }
        
        /* 移除了AI控制按钮相关样式 - 功能已移至设置面板 */
        
        /* 智能命令解释样式 */
        .command-explanation-container {
            margin: 8px 0;
            background: rgba(255, 193, 7, 0.1);
            border: 1px solid rgba(255, 193, 7, 0.3);
            border-radius: 6px;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        .explanation-header {
            padding: 8px 12px;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .explanation-icon {
            font-size: 0.9rem;
            color: #ffc107;
        }
        
        .explanation-text {
            flex: 1;
            font-size: 0.85rem;
            color: #f8f9fa;
            line-height: 1.3;
        }
        
        .hide-explanation {
            background: none;
            border: none;
            color: #adb5bd;
            font-size: 1.2rem;
            cursor: pointer;
            padding: 0;
            width: 20px;
            height: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 3px;
            transition: all 0.2s ease;
        }
        
        .hide-explanation:hover {
            background: rgba(255,255,255,0.1);
            color: #fff;
        }
        
        /* 设置面板样式 */
        .settings-section {
            margin-bottom: 24px;
            padding: 16px;
            background: rgba(255,255,255,0.05);
            border-radius: 8px;
            border: 1px solid rgba(255,255,255,0.1);
        }
        
        .settings-section h4 {
            margin: 0 0 16px 0;
            color: #e0e0e0;
            font-size: 1rem;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .settings-group {
            display: flex;
            flex-direction: column;
            gap: 16px;
        }
        
        .setting-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px;
            background: rgba(255,255,255,0.03);
            border-radius: 6px;
            border: 1px solid rgba(255,255,255,0.08);
        }
        
        .setting-label {
            display: flex;
            align-items: center;
            gap: 12px;
            flex: 1;
        }
        
        .setting-icon {
            font-size: 1.2rem;
        }
        
        .setting-title {
            font-weight: 500;
            color: #f0f0f0;
            font-size: 0.95rem;
        }
        
        .setting-description {
            color: #aaa;
            font-size: 0.85rem;
            margin-left: 8px;
        }
        
        /* 切换开关样式 */
        .toggle-switch {
            position: relative;
            display: inline-block;
            width: 50px;
            height: 24px;
        }
        
        .toggle-switch input {
            opacity: 0;
            width: 0;
            height: 0;
        }
        
        .slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #555;
            transition: 0.3s;
            border-radius: 24px;
        }
        
        .slider:before {
            position: absolute;
            content: "";
            height: 18px;
            width: 18px;
            left: 3px;
            bottom: 3px;
            background-color: white;
            transition: 0.3s;
            border-radius: 50%;
        }
        
        .toggle-switch input:checked + .slider {
            background-color: #27ae60;
        }
        
        .toggle-switch input:checked + .slider:before {
            transform: translateX(26px);
        }
        
        .slider:hover {
            opacity: 0.8;
        }
        
        /* 弹窗样式 */
        .modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.7);
            z-index: 1000;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        
        .modal-content {
            background-color: #2d2d30;
            border: 1px solid #3c3c3c;
            border-radius: 5px;
            width: 400px;
            max-width: 90%;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
        }
        
        .modal-header {
            padding: 15px;
            border-bottom: 1px solid #3c3c3c;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .modal-header h3 {
            margin: 0;
            color: #d4d4d4;
        }
        
        .close {
            color: #aaa;
            font-size: 24px;
            cursor: pointer;
        }
        
        .close:hover {
            color: #fff;
        }
        
        .modal-body {
            padding: 15px;
        }
        
        .directory-list, .command-list {
            max-height: 300px;
            overflow-y: auto;
        }
        
        .directory-item, .command-item {
            padding: 10px;
            cursor: pointer;
            border-bottom: 1px solid #3c3c3c;
            color: #d4d4d4;
            font-family: 'Courier New', monospace;
            font-size: 14px;
        }
        
        .directory-item:hover, .command-item:hover {
            background-color: #3c3c3c;
        }
        
        .directory-item:last-child, .command-item:last-child {
            border-bottom: none;
        }
        
        /* 历史命令表格样式 */
        .history-table-container {
            max-height: 300px;
            overflow-y: auto;
        }
        
        .history-table {
            width: 100%;
            border-collapse: collapse;
            color: #d4d4d4;
            font-family: 'Courier New', monospace;
            font-size: 14px;
        }
        
        .history-table th {
            background-color: #3c3c3c;
            padding: 10px;
            text-align: left;
            border-bottom: 1px solid #555;
        }
        
        .history-table td {
            padding: 8px 10px;
            border-bottom: 1px solid #3c3c3c;
        }
        
        .history-table tr:hover {
            background-color: #3c3c3c;
        }
        
        .history-table .command-cell {
            word-break: break-all;
        }
        
        .history-table .explanation-cell {
            font-size: 0.9em;
            color: #9cdcfe;
            max-width: 300px;
        }
        
        /* 历史命令解释内容样式 */
        .explanation-content {
            display: flex;
            align-items: flex-start;
            gap: 6px;
        }
        
        .explanation-content .explanation-icon {
            color: #ffc107;
            font-size: 0.8rem;
            flex-shrink: 0;
        }
        
        .explanation-content .explanation-text {
            color: #f8f9fa;
            font-size: 0.8rem;
            line-height: 1.3;
            word-wrap: break-word;
        }
        
        .no-explanation {
            color: #6c757d;
            font-style: italic;
            font-size: 0.8rem;
        }
        
        .history-actions button {
            background-color: #3c3c3c;
            color: #d4d4d4;
            border: 1px solid #555;
            padding: 3px 6px;
            border-radius: 3px;
            cursor: pointer;
            font-size: 0.8em;
            margin-right: 5px;
        }
        
        .history-actions button:hover {
            background-color: #4d4d4d;
        }
        
        .pagination button {
            background-color: #3c3c3c;
            color: #d4d4d4;
            border: 1px solid #555;
            padding: 5px 10px;
            border-radius: 3px;
            cursor: pointer;
        }
        
        .pagination button:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
        
        .pagination button:hover:not(:disabled) {
            background-color: #4d4d4d;
        }


        /* 右侧AI面板样式 */
        .ai-panel {
            width: 350px;
            background-color: #252526;
            border-left: 1px solid #3c3c3c;
            display: flex;
            flex-direction: column;
            height: 100%;
        }

        .ai-panel-header {
            background-color: #2d2d30;
            padding: 12px 15px;
            border-bottom: 1px solid #3c3c3c;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .ai-panel-title {
            display: flex;
            align-items: center;
            gap: 8px;
            font-weight: 500;
            font-size: 0.95rem;
        }

        /* AI模型选择区域样式 */
        .ai-model-selector-area {
            background-color: #2d2d30;
            padding: 12px 15px;
            border-top: 1px solid #3c3c3c;
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 15px;
        }

        .model-selector-label {
            display: flex;
            align-items: center;
            gap: 6px;
            font-size: 0.85rem;
            color: #d4d4d4;
            font-weight: 500;
            min-width: fit-content;
        }

        .model-icon {
            font-size: 14px;
        }

        .model-selector {
            background-color: #3c3c3c;
            color: #d4d4d4;
            border: 1px solid #555;
            padding: 6px 12px;
            border-radius: 4px;
            font-size: 0.85rem;
            outline: none;
            flex: 1;
            max-width: 150px;
        }

        .model-selector:focus {
            border-color: #007acc;
        }

        .model-status {
            display: flex;
            align-items: center;
            gap: 6px;
            font-size: 0.8rem;
            min-width: fit-content;
        }

        .status-indicator {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            flex-shrink: 0;
        }

        .status-indicator.connected {
            background-color: #b5cea8;
            box-shadow: 0 0 4px rgba(181, 206, 168, 0.6);
        }

        .status-indicator.disconnected {
            background-color: #f48771;
            box-shadow: 0 0 4px rgba(244, 135, 113, 0.6);
        }

        .status-indicator.connecting {
            background-color: #ffd700;
            animation: pulse 1.5s ease-in-out infinite;
        }

        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.5; }
        }

        .status-text {
            color: #888888;
        }

        .ai-icon {
            font-size: 18px;
        }

        .close-ai-panel {
            background: none;
            border: none;
            color: #888888;
            font-size: 20px;
            cursor: pointer;
            padding: 0;
            width: 24px;
            height: 24px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .close-ai-panel:hover {
            color: #d4d4d4;
        }

        .ai-chat-messages {
            flex: 1;
            padding: 15px;
            overflow-y: auto;
            display: flex;
            flex-direction: column;
            gap: 15px;
        }

        .ai-message, .user-message {
            display: flex;
            gap: 10px;
        }

        .user-message {
            flex-direction: row-reverse;
        }

        .system-message {
            display: flex;
            justify-content: center;
            margin: 10px 0;
        }

        .system-content {
            background-color: rgba(86, 156, 214, 0.1);
            border: 1px solid rgba(86, 156, 214, 0.3);
            border-radius: 6px;
            padding: 8px 12px;
            text-align: center;
        }

        .system-text {
            font-size: 0.85rem;
            color: #569cd6;
            margin-bottom: 2px;
        }

        .message-avatar {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            background-color: #3c3c3c;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 16px;
            flex-shrink: 0;
        }

        .user-message .message-avatar {
            background-color: #007acc;
        }

        .message-content {
            flex: 1;
            min-width: 0;
        }

        .user-message .message-content {
            text-align: right;
        }

        .message-text {
            background-color: #2d2d30;
            padding: 10px 12px;
            border-radius: 8px;
            margin-bottom: 4px;
            font-size: 0.9rem;
            line-height: 1.4;
        }

        .user-message .message-text {
            background-color: #005a9e;
        }

        .message-time {
            font-size: 0.75rem;
            color: #888888;
            padding: 0 12px;
        }

        .command-blocks {
            margin-top: 10px;
            display: flex;
            flex-direction: column;
            gap: 8px;
        }

        .command-block {
            background-color: #252526;
            border: 1px solid #3c3c3c;
            border-radius: 6px;
            padding: 10px;
            font-family: 'Courier New', monospace;
            font-size: 0.85rem;
        }

        .command-header {
            display: flex;
            justify-content: between;
            align-items: center;
            margin-bottom: 6px;
        }

        .command-text {
            color: #4fc1ff;
            font-weight: 500;
            flex: 1;
            word-break: break-all;
        }

        .command-run-btn {
            background-color: #0e639c;
            color: white;
            border: none;
            border-radius: 4px;
            padding: 4px 10px;
            font-size: 0.75rem;
            cursor: pointer;
            margin-left: 10px;
            transition: background-color 0.2s;
        }

        .command-run-btn:hover {
            background-color: #1177bb;
        }

        .command-run-btn:active {
            background-color: #005a9e;
        }

        .command-explain {
            color: #cccccc;
            font-size: 0.8rem;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            line-height: 1.3;
            margin-top: 4px;
        }

        .ai-chat-input {
            padding: 15px;
            border-top: 1px solid #3c3c3c;
            display: flex;
            gap: 10px;
        }

        .ai-chat-input input {
            flex: 1;
            background-color: #2d2d30;
            border: 1px solid #3c3c3c;
            color: #d4d4d4;
            padding: 8px 12px;
            border-radius: 4px;
            font-size: 0.9rem;
            outline: none;
        }

        .ai-chat-input input:focus {
            border-color: #007acc;
        }

        .ai-chat-input button {
            background-color: #007acc;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 0.9rem;
        }

        .ai-chat-input button:hover {
            background-color: #005a9e;
        }

        /* AI模型配置弹窗样式 */
        .models-section {
            margin-bottom: 20px;
        }

        .models-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }

        .models-header h4 {
            margin: 0;
            color: #d4d4d4;
            font-size: 1.1rem;
        }

        .add-model-btn {
            background-color: #007acc;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 0.9rem;
        }

        .add-model-btn:hover {
            background-color: #005a9e;
        }

        .models-list {
            display: flex;
            flex-direction: column;
            gap: 10px;
        }

        .model-item {
            background-color: #2d2d30;
            border: 1px solid #3c3c3c;
            border-radius: 6px;
            padding: 15px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .model-info {
            flex: 1;
        }

        .model-name {
            font-weight: 500;
            font-size: 1rem;
            color: #d4d4d4;
            margin-bottom: 4px;
        }

        .model-details {
            font-size: 0.85rem;
            color: #888888;
            margin-bottom: 6px;
        }

        .model-status {
            font-size: 0.8rem;
            font-weight: 500;
        }

        .model-status.connected {
            color: #b5cea8;
        }

        .model-status.disconnected {
            color: #f48771;
        }

        .model-actions {
            display: flex;
            gap: 8px;
        }

        .model-actions button {
            background-color: #3c3c3c;
            color: #d4d4d4;
            border: 1px solid #555;
            padding: 6px 12px;
            border-radius: 3px;
            cursor: pointer;
            font-size: 0.85rem;
        }

        .model-actions button:hover:not(:disabled) {
            background-color: #4d4d4d;
        }

        .model-actions button:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        .test-btn:hover:not(:disabled) {
            background-color: #007acc !important;
        }

        .delete-btn:hover {
            background-color: #c5443a !important;
        }

        /* 模型配置表单样式 */
        .model-form-section {
            margin-top: 20px;
        }

        .form-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 1px solid #3c3c3c;
        }

        .form-header h4 {
            margin: 0;
            color: #d4d4d4;
        }

        .back-btn {
            background-color: #555;
            color: #d4d4d4;
            border: none;
            padding: 6px 12px;
            border-radius: 3px;
            cursor: pointer;
            font-size: 0.85rem;
        }

        .back-btn:hover {
            background-color: #666;
        }

        .model-form {
            max-width: 600px;
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
            color: #d4d4d4;
            font-weight: 500;
        }

        .form-group input {
            width: 100%;
            background-color: #2d2d30;
            color: #d4d4d4;
            border: 1px solid #3c3c3c;
            padding: 10px 12px;
            border-radius: 4px;
            font-size: 0.9rem;
            outline: none;
        }

        .form-group input:focus {
            border-color: #007acc;
        }

        .form-actions {
            display: flex;
            gap: 10px;
            margin-top: 20px;
            align-items: center;
        }

        .test-config-btn {
            background-color: #569cd6;
            color: white;
            border: none;
            padding: 10px 16px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 0.9rem;
        }

        .test-config-btn:hover {
            background-color: #4a8bc2;
        }

        .save-btn {
            background-color: #007acc;
            color: white;
            border: none;
            padding: 10px 16px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 0.9rem;
        }

        .save-btn:hover {
            background-color: #005a9e;
        }

        .cancel-btn {
            background-color: #555;
            color: #d4d4d4;
            border: none;
            padding: 10px 16px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 0.9rem;
        }

        .cancel-btn:hover {
            background-color: #666;
        }

        .test-result {
            margin-top: 15px;
            padding: 10px;
            border-radius: 4px;
            font-size: 0.9rem;
        }

        .test-result.success {
            background-color: rgba(181, 206, 168, 0.1);
            border: 1px solid #b5cea8;
            color: #b5cea8;
        }

        .test-result.error {
            background-color: rgba(244, 135, 113, 0.1);
            border: 1px solid #f48771;
            color: #f48771;
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>智能AI终端</h1>
        <div>终端版本 1.0.0</div>
    </div>
    
    <div class="status-bar">
        
    </div>
    
    <div class="container">
        
        <!-- 终端区域 -->
        <div class="terminal-area">
            <div class="terminal-header">
                <div class="terminal-tabs">
                    <div class="terminal-tab active">终端 1</div>
                    <div class="terminal-tab">终端 2</div>
                    <div class="terminal-tab">+</div>
                </div>
                <div>bash</div>
            </div>
            
            <div class="terminal-content">
                <div class="command-line"><span class="prompt">developer@macbook</span><span>~/projects/ai-terminal $</span> 欢迎使用智能AI终端</div>
                <div class="command-output">系统已就绪，具备上下文感知和智能补全功能</div>
                <div class="command-line"><span class="prompt">developer@macbook</span><span>~/projects/ai-terminal $</span> ls -la</div>
                <div class="command-output">total 24
drwxr-xr-x  5 developer  staff   160  8 30 10:30 .
drwxr-xr-x  8 developer  staff   256  8 30 10:25 ..
-rw-r--r--  1 developer  staff  1024  8 30 10:30 package.json
drwxr-xr-x  3 developer  staff    96  8 30 10:28 src
drwxr-xr-x  4 developer  staff   128  8 30 10:29 dist</div>
                <div class="command-explanation-container">
                    <div class="explanation-header">
                        <span class="explanation-icon">💡</span>
                        <span class="explanation-text">列出当前目录的所有文件和文件夹，包括隐藏文件，以长格式显示详细信息</span>
                        <button class="hide-explanation" onclick="this.parentElement.parentElement.style.display='none'">×</button>
                    </div>
                </div>
                <div class="command-line"><span class="prompt">developer@macbook</span><span>~/projects/ai-terminal $</span> git status</div>
                <div class="command-output">On branch main
Your branch is up to date with 'origin/main'.

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git restore <file>..." to discard changes in working directory)
    modified:   src/index.js

no changes added to commit (use "git add" and/or "git commit -a")</div>
                <div class="ai-suggestion">
                    <strong>AI建议:</strong> 检测到未提交的更改，建议执行 "git add src/index.js" 然后提交
                </div>
                <div class="command-line"><span class="prompt">developer@macbook</span><span>~/projects/ai-terminal $</span> pwd</div>
                <div class="command-output">/Users/developer/projects/ai-terminal</div>
                <!-- pwd是简单命令，不显示解释 -->
                
                <div class="command-line"><span class="prompt">developer@macbook</span><span>~/projects/ai-terminal $</span> npm run build</div>
                <div class="command-output">> ai-terminal@1.0.0 build
> webpack --mode production

Hash: a1b2c3d4e5f
Version: webpack 5.76.0
Time: 2345ms
Built at: 2023-08-30 10:35:45
    Asset      Size  Chunks             Chunk Names
bundle.js  1.23 MiB       0  [emitted]  main
Entrypoint main = bundle.js</div>
                <div class="command-explanation-container">
                    <div class="explanation-header">
                        <span class="explanation-icon">💡</span>
                        <span class="explanation-text">Node Package Manager命令，执行构建脚本将源代码编译打包成生产环境可用的文件</span>
                        <button class="hide-explanation" onclick="this.parentElement.parentElement.style.display='none'">×</button>
                    </div>
                </div>
                <div class="command-line"><span class="prompt">developer@macbook</span><span>~/projects/ai-terminal $</span> </div>
            </div>
            
            <!-- 上下文建议区域 -->
            <div class="context-suggestions" id="contextSuggestions">
                <div class="suggestions-header">
                    <span class="suggestions-title">🧠 基于命令历史的建议</span>
                    <span class="suggestions-info">分析最近 3 条命令</span>
                    <button class="toggle-suggestions" id="toggleSuggestions">︽</button>
                </div>
                <div class="suggestions-content" id="suggestionsContent">
                    <div class="command-sequence">
                        <div class="sequence-item">
                            <span class="sequence-number">1</span>
                            <span class="sequence-command">git status</span>
                            <span class="sequence-result">✓</span>
                        </div>
                        <div class="sequence-item">
                            <span class="sequence-number">2</span>
                            <span class="sequence-command">npm run build</span>
                            <span class="sequence-result">✓</span>
                        </div>
                        <div class="sequence-item current">
                            <span class="sequence-number">3</span>
                            <span class="sequence-command">ls -la</span>
                            <span class="sequence-result">✓</span>
                        </div>
                    </div>
                    <div class="next-suggestions">
                        <div class="suggestion-title">💡 建议下一步操作：</div>
                        <div class="suggestion-items">
                            <div class="suggestion-item clickable" data-cmd="git add .">
                                <span class="suggestion-icon">📁</span>
                                <div class="suggestion-content">
                                    <div class="suggestion-cmd">git add .</div>
                                    <div class="suggestion-reason">检测到文件修改，添加到暂存区</div>
                                </div>
                                <span class="suggestion-confidence">85%</span>
                            </div>
                            <div class="suggestion-item clickable" data-cmd="npm run test">
                                <span class="suggestion-icon">🧪</span>
                                <div class="suggestion-content">
                                    <div class="suggestion-cmd">npm run test</div>
                                    <div class="suggestion-reason">构建完成后通常需要运行测试</div>
                                </div>
                                <span class="suggestion-confidence">72%</span>
                            </div>
                            <div class="suggestion-item clickable" data-cmd="git log --oneline">
                                <span class="suggestion-icon">📊</span>
                                <div class="suggestion-content">
                                    <div class="suggestion-cmd">git log --oneline</div>
                                    <div class="suggestion-reason">查看提交历史</div>
                                </div>
                                <span class="suggestion-confidence">45%</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 功能按钮区域 -->
            <div class="toolbar">
                <div class="toolbar-buttons">
                    <button class="toolbar-button files-button" id="filesButton">
                        <span class="button-icon">📁</span>
                        <span class="button-text">文件管理</span>
                    </button>
                    
                    <div class="toolbar-group">
                        <button class="toolbar-button primary-button" id="commandCenterButton">
                            <span class="button-icon">⚡</span>
                            <span class="button-text">命令中心</span>
                            <span class="dropdown-arrow">▼</span>
                        </button>
                        <div class="dropdown-menu" id="commandCenterMenu" style="display: none;">
                            <div class="dropdown-item" data-action="common-commands">⚡ 常用命令</div>
                            <div class="dropdown-item" data-action="history">📚 历史命令</div>
                        </div>
                    </div>
                    
                    <button class="toolbar-button ai-button" id="aiButton">
                        <span class="button-icon">🤖</span>
                        <span class="button-text">AI助手</span>
                    </button>
                    
                    <button class="toolbar-button" id="settingsButton">
                        <span class="button-icon">⚙️</span>
                        <span class="button-text">设置</span>
                    </button>
                </div>
            </div>
            
            <!-- 智能输入区域 -->
            <div class="smart-input-area">
                <div class="command-input-container">
                    <div class="command-suggestions" style="display: none;">
                        <div class="suggestion-item">git add src/index.js && git commit -m "Update index.js functionality" <span class="suggestion-confidence">92%</span></div>
                        <div class="suggestion-item active">git add . && git commit -m "Add new features" <span class="suggestion-confidence">87%</span></div>
                        <div class="suggestion-item">npm run test -- --coverage <span class="suggestion-confidence">78%</span></div>
                    </div>
                    <span class="prompt">developer@macbook</span><span>~/projects/ai-terminal $</span> <input type="text" class="command-input" value="" placeholder="输入命令...">
                </div>
            </div>
            
            <!-- 目录选择弹窗 -->
            <div class="modal" id="folderModal" style="display: none;">
                <div class="modal-content">
                    <div class="modal-header">
                        <h3>选择目录</h3>
                        <span class="close" id="closeFolderModal">&times;</span>
                    </div>
                    <div class="modal-body">
                        <div class="directory-list">
                            <div class="directory-item" data-path="~/projects">~/projects</div>
                            <div class="directory-item" data-path="~/documents">~/documents</div>
                            <div class="directory-item" data-path="~/downloads">~/downloads</div>
                            <div class="directory-item" data-path="~/desktop">~/desktop</div>
                            <div class="directory-item" data-path="~/workspace">~/workspace</div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 命令选择弹窗 -->
            <div class="modal" id="commandModal" style="display: none;">
                <div class="modal-content">
                    <div class="modal-header">
                        <h3>常用命令</h3>
                        <span class="close" id="closeCommandModal">&times;</span>
                    </div>
                    <div class="modal-body">
                        <div class="command-list">
                            <div class="command-item" data-cmd="ls -la">ls -la</div>
                            <div class="command-item" data-cmd="git status">git status</div>
                            <div class="command-item" data-cmd="git log --oneline">git log --oneline</div>
                            <div class="command-item" data-cmd="npm run dev">npm run dev</div>
                            <div class="command-item" data-cmd="npm run build">npm run build</div>
                            <div class="command-item" data-cmd="docker ps">docker ps</div>
                            <div class="command-item" data-cmd="docker-compose up">docker-compose up</div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 历史命令弹窗 -->
            <div class="modal" id="historyModal" style="display: none;">
                <div class="modal-content" style="width: 800px;">
                    <div class="modal-header">
                        <h3>历史命令</h3>
                        <span class="close" id="closeHistoryModal">&times;</span>
                    </div>
                    <div class="modal-body">
                        <div style="margin-bottom: 15px;">
                            <input type="text" id="historySearch" placeholder="搜索历史命令..." style="width: 100%; padding: 8px; background: #3c3c3c; border: 1px solid #555; color: #d4d4d4; border-radius: 3px;">
                        </div>
                        <div class="history-table-container">
                            <table class="history-table">
                                <thead>
                                    <tr>
                                        <th style="width: 150px;">时间</th>
                                        <th style="width: 100px;">会话ID</th>
                                        <th style="width: 250px;">命令</th>
                                        <th>解释</th>
                                        <th style="width: 150px;">操作</th>
                                    </tr>
                                </thead>
                                <tbody id="historyTableBody">
                                    <!-- 历史记录将通过JavaScript动态添加 -->
                                </tbody>
                            </table>
                        </div>
                        <div class="pagination" style="margin-top: 15px; text-align: center;">
                            <button id="prevPage" disabled>上一页</button>
                            <span id="pageInfo" style="margin: 0 10px;">第 1 页</span>
                            <button id="nextPage">下一页</button>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 命令输出弹窗 -->
            <div class="modal" id="outputModal" style="display: none;">
                <div class="modal-content" style="width: 800px;">
                    <div class="modal-header">
                        <h3>命令输出</h3>
                        <span class="close" id="closeOutputModal">&times;</span>
                    </div>
                    <div class="modal-body">
                        <div style="margin-bottom: 10px;">
                            <strong>命令:</strong> <span id="outputCommand"></span>
                        </div>
                        <div style="margin-bottom: 10px;">
                            <strong>执行时间:</strong> <span id="outputTimestamp"></span>
                        </div>
                        <div style="margin-bottom: 15px;">
                            <strong>输出内容:</strong>
                        </div>
                        <div id="outputContent" style="background: #1e1e1e; color: #d4d4d4; padding: 15px; border-radius: 5px; font-family: 'Courier New', monospace; font-size: 14px; white-space: pre-wrap; max-height: 400px; overflow-y: auto;">
                            <!-- 输出内容将通过JavaScript动态添加 -->
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 右侧AI对话面板 -->
        <div class="ai-panel" id="aiPanel" style="display: none;">
            <div class="ai-panel-header">
                <div class="ai-panel-title">
                    <span class="ai-icon">🤖</span>
                    AI 助手
                </div>
                <button class="close-ai-panel" id="closeAiPanel">×</button>
            </div>
            
            <div class="ai-chat-messages" id="aiChatMessages">
                <div class="ai-message">
                    <div class="message-avatar">🤖</div>
                    <div class="message-content">
                        <div class="message-text">你好！我是AI终端助手，可以帮你解释命令、提供建议或回答技术问题。有什么需要帮助的吗？</div>
                        <div class="message-time">刚刚</div>
                    </div>
                </div>
            </div>
            
            <div class="ai-model-selector-area">
                <div class="model-selector-label">
                    <span class="model-icon">⚙️</span>
                    <span>对话模型:</span>
                </div>
                <select class="model-selector" id="modelSelector">
                    <option value="gpt-4">GPT-4</option>
                    <option value="claude-3">Claude-3</option>
                    <option value="local-llm">本地模型</option>
                </select>
                <div class="model-status" id="modelStatus">
                    <span class="status-indicator connected"></span>
                    <span class="status-text">已连接</span>
                </div>
            </div>
            
            <div class="ai-chat-input">
                <input type="text" id="aiChatInput" placeholder="问我任何关于终端或编程的问题..." />
                <button id="sendChatBtn">发送</button>
            </div>
        </div>

        <!-- AI模型配置弹窗 -->
        <div class="modal" id="settingsModal" style="display: none;">
            <div class="modal-content" style="width: 800px; max-height: 80vh;">
                <div class="modal-header">
                    <h3>设置</h3>
                    <span class="close" id="closeSettingsModal">&times;</span>
                </div>
                <div class="modal-body">
                    <!-- AI功能设置 -->
                    <div class="settings-section">
                        <h4>🤖 AI功能设置</h4>
                        <div class="settings-group">
                            <div class="setting-item">
                                <div class="setting-label">
                                    <span class="setting-icon">🧠</span>
                                    <span class="setting-title">上下文感知</span>
                                    <span class="setting-description">基于命令历史提供智能建议</span>
                                </div>
                                <label class="toggle-switch">
                                    <input type="checkbox" id="contextAwareSetting" checked>
                                    <span class="slider"></span>
                                </label>
                            </div>
                            <div class="setting-item">
                                <div class="setting-label">
                                    <span class="setting-icon">💡</span>
                                    <span class="setting-title">命令解释</span>
                                    <span class="setting-description">对复杂命令提供智能解释</span>
                                </div>
                                <label class="toggle-switch">
                                    <input type="checkbox" id="commandExplainSetting" checked>
                                    <span class="slider"></span>
                                </label>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 模型管理 -->
                    <div class="settings-section">
                        <h4>🔧 AI模型管理</h4>
                        <div class="models-section" id="modelsListSection">
                        <div class="models-header">
                            <h4>已配置的模型</h4>
                            <button class="add-model-btn" id="addModelBtn">+ 添加模型</button>
                        </div>
                        <div class="models-list" id="modelsList">
                            <div class="model-item">
                                <div class="model-info">
                                    <div class="model-name">GPT-4</div>
                                    <div class="model-details">api.openai.com • gpt-4 • 默认模型</div>
                                    <div class="model-status connected">● 已连接</div>
                                </div>
                                <div class="model-actions">
                                    <button class="test-btn">检测</button>
                                    <button class="edit-btn">编辑</button>
                                    <button class="delete-btn">删除</button>
                                </div>
                            </div>
                            <div class="model-item">
                                <div class="model-info">
                                    <div class="model-name">Claude-3</div>
                                    <div class="model-details">api.anthropic.com • claude-3-sonnet • 备用模型</div>
                                    <div class="model-status disconnected">● 未配置</div>
                                </div>
                                <div class="model-actions">
                                    <button class="test-btn" disabled>检测</button>
                                    <button class="edit-btn">编辑</button>
                                    <button class="delete-btn">删除</button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 模型配置表单 -->
                    <div class="model-form-section" id="modelFormSection" style="display: none;">
                        <div class="form-header">
                            <h4 id="formTitle">添加新模型</h4>
                            <button class="back-btn" id="backToListBtn">← 返回列表</button>
                        </div>
                        <form class="model-form" id="modelForm">
                            <div class="form-group">
                                <label for="modelDisplayName">显示名称</label>
                                <input type="text" id="modelDisplayName" placeholder="例如：GPT-4" required>
                            </div>
                            <div class="form-group">
                                <label for="modelName">模型名称</label>
                                <input type="text" id="modelName" placeholder="例如：gpt-4" required>
                            </div>
                            <div class="form-group">
                                <label for="apiUrl">API地址</label>
                                <input type="url" id="apiUrl" placeholder="例如：https://api.openai.com/v1" required>
                            </div>
                            <div class="form-group">
                                <label for="apiKey">API Key</label>
                                <input type="password" id="apiKey" placeholder="请输入API Key" required>
                            </div>
                            <div class="form-actions">
                                <button type="button" class="test-config-btn" id="testConfigBtn">🔍 测试连接</button>
                                <button type="button" class="cancel-btn" id="cancelFormBtn">取消</button>
                                <button type="submit" class="save-btn">保存配置</button>
                            </div>
                            <div class="test-result" id="testResult" style="display: none;">
                                <!-- 测试结果将在这里显示 -->
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script>
        // 获取所有按钮和弹窗元素
        const filesButton = document.getElementById('filesButton');
        const commandCenterButton = document.getElementById('commandCenterButton');
        const commandCenterMenu = document.getElementById('commandCenterMenu');
        const aiButton = document.getElementById('aiButton');
        const settingsButton = document.getElementById('settingsButton');
        
        const folderModal = document.getElementById('folderModal');
        const commandModal = document.getElementById('commandModal');
        const historyModal = document.getElementById('historyModal');
        const outputModal = document.getElementById('outputModal');
        const closeFolderModal = document.getElementById('closeFolderModal');
        const closeCommandModal = document.getElementById('closeCommandModal');
        const closeHistoryModal = document.getElementById('closeHistoryModal');
        const closeOutputModal = document.getElementById('closeOutputModal');
        const settingsModal = document.getElementById('settingsModal');
        const closeSettingsModal = document.getElementById('closeSettingsModal');
        
        // 目录弹窗相关元素
        const directoryItems = document.querySelectorAll('.directory-item');
        const commandItems = document.querySelectorAll('.command-item');
        
        // 输入框元素
        const commandInput = document.querySelector('.command-input');
        const terminalContent = document.querySelector('.terminal-content');
        const commandSuggestions = document.querySelector('.command-suggestions');
        
        // 文件管理按钮处理
        filesButton.addEventListener('click', () => {
            folderModal.style.display = 'flex';
        });
        
        // 命令中心下拉菜单处理
        commandCenterButton.addEventListener('click', (e) => {
            e.stopPropagation();
            const isVisible = commandCenterMenu.style.display === 'block';
            commandCenterMenu.style.display = isVisible ? 'none' : 'block';
        });
        
        // 点击命令中心菜单项
        commandCenterMenu.addEventListener('click', (e) => {
            const action = e.target.dataset.action;
            if (action === 'common-commands') {
                commandModal.style.display = 'flex';
            } else if (action === 'history') {
                historyModal.style.display = 'flex';
                currentPage = 1;
                filterAndDisplayHistory();
            }
            commandCenterMenu.style.display = 'none';
        });
        
        // 点击其他地方关闭下拉菜单
        document.addEventListener('click', () => {
            commandCenterMenu.style.display = 'none';
        });
        
        // 输入框事件监听
        commandInput.addEventListener('input', () => {
            const inputValue = commandInput.value.trim();
            
            // 如果输入框为空，隐藏建议列表
            if (inputValue === '') {
                commandSuggestions.style.display = 'none';
            } else {
                // 显示建议列表
                commandSuggestions.style.display = 'block';
                
                // 这里可以添加更复杂的建议过滤逻辑
                // 基于输入内容过滤建议项
                filterSuggestions(inputValue);
            }
        });
        
        // 点击其他地方隐藏建议列表
        document.addEventListener('click', (event) => {
            if (!commandInput.contains(event.target) && !commandSuggestions.contains(event.target)) {
                commandSuggestions.style.display = 'none';
            }
        });
        
        // 过滤建议项
        function filterSuggestions(inputValue) {
            const suggestionItems = document.querySelectorAll('.suggestion-item');
            let hasVisibleSuggestions = false;
            
            suggestionItems.forEach(item => {
                const commandText = item.textContent.toLowerCase();
                if (commandText.includes(inputValue.toLowerCase())) {
                    item.style.display = 'block';
                    hasVisibleSuggestions = true;
                } else {
                    item.style.display = 'none';
                }
            });
            
            // 如果没有匹配的建议，隐藏建议列表
            if (!hasVisibleSuggestions) {
                commandSuggestions.style.display = 'none';
            } else {
                commandSuggestions.style.display = 'block';
            }
        }
        
                
        // 关闭目录弹窗
        closeFolderModal.addEventListener('click', () => {
            folderModal.style.display = 'none';
        });
        
        // 关闭命令弹窗
        closeCommandModal.addEventListener('click', () => {
            commandModal.style.display = 'none';
        });
        
        // 关闭历史命令弹窗
        closeHistoryModal.addEventListener('click', () => {
            historyModal.style.display = 'none';
        });
        
        // 关闭输出弹窗
        closeOutputModal.addEventListener('click', () => {
            outputModal.style.display = 'none';
        });
        
        // 点击弹窗外部关闭弹窗
        window.addEventListener('click', (event) => {
            if (event.target === folderModal) {
                folderModal.style.display = 'none';
            }
            if (event.target === commandModal) {
                commandModal.style.display = 'none';
            }
            if (event.target === historyModal) {
                historyModal.style.display = 'none';
            }
            if (event.target === outputModal) {
                outputModal.style.display = 'none';
            }
        });
        
        // 目录选择功能
        directoryItems.forEach(item => {
            item.addEventListener('click', () => {
                const path = item.getAttribute('data-path');
                // 在终端中显示命令
                const commandLine = document.createElement('div');
                commandLine.className = 'command-line';
                commandLine.innerHTML = '<span class="prompt">developer@macbook</span><span>~/projects/ai-terminal $</span> cd ' + path;
                terminalContent.appendChild(commandLine);
                
                // 显示执行结果
                const outputLine = document.createElement('div');
                outputLine.className = 'command-output';
                outputLine.textContent = '已切换到目录: ' + path;
                terminalContent.appendChild(outputLine);
                
                // 滚动到底部
                terminalContent.scrollTop = terminalContent.scrollHeight;
                
                // 关闭弹窗
                folderModal.style.display = 'none';
                
                // 更新输入框提示
                commandInput.placeholder = "输入命令... (当前目录: " + path + ")";
            });
        });
        
        // 命令选择功能
        commandItems.forEach(item => {
            item.addEventListener('click', () => {
                const cmd = item.getAttribute('data-cmd');
                // 在终端中显示命令
                const commandLine = document.createElement('div');
                commandLine.className = 'command-line';
                commandLine.innerHTML = '<span class="prompt">developer@macbook</span><span>~/projects/ai-terminal $</span> ' + cmd;
                terminalContent.appendChild(commandLine);
                
                // 模拟命令执行结果
                let outputLine = document.createElement('div');
                outputLine.className = 'command-output';
                
                // 根据不同命令显示不同结果
                if (cmd === 'ls -la') {
                    outputLine.textContent = 'total 24\ndrwxr-xr-x  5 developer  staff   160  8 30 10:30 .\ndrwxr-xr-x  8 developer  staff   256  8 30 10:25 ..\n-rw-r--r--  1 developer  staff  1024  8 30 10:30 package.json\ndrwxr-xr-x  3 developer  staff    96  8 30 10:28 src\ndrwxr-xr-x  4 developer  staff   128  8 30 10:29 dist';
                } else if (cmd === 'git status') {
                    outputLine.textContent = 'On branch main\nYour branch is up to date with \'origin/main\'.\n\nChanges not staged for commit:\n  (use "git add <file>..." to update what will be committed)\n  (use "git restore <file>..." to discard changes in working directory)\n\tmodified:   src/index.js\n\nno changes added to commit (use "git add" and/or "git commit -a")';
                } else if (cmd.startsWith('npm run')) {
                    outputLine.textContent = '> ai-terminal@1.0.0 ' + cmd + '\n> ' + cmd.replace('npm run ', '') + '\n\n正在执行任务...';
                } else {
                    outputLine.textContent = '命令已执行: ' + cmd;
                }
                
                terminalContent.appendChild(outputLine);
                
                // 滚动到底部
                terminalContent.scrollTop = terminalContent.scrollHeight;
                
                // 关闭弹窗
                commandModal.style.display = 'none';
            });
        });
        
        // 历史命令功能相关元素
        const historyTableBody = document.getElementById('historyTableBody');
        const historySearch = document.getElementById('historySearch');
        const prevPageBtn = document.getElementById('prevPage');
        const nextPageBtn = document.getElementById('nextPage');
        const pageInfo = document.getElementById('pageInfo');
        
        // 命令输出功能相关元素
        const outputCommand = document.getElementById('outputCommand');
        const outputTimestamp = document.getElementById('outputTimestamp');
        const outputContent = document.getElementById('outputContent');
        
        // 模拟历史命令数据
        let commandHistory = [
            { id: 1, sessionId: 'session_001', timestamp: '2023-08-30 10:30:15', command: 'ls -la', output: 'total 24\ndrwxr-xr-x  5 developer  staff   160  8 30 10:30 .\ndrwxr-xr-x  8 developer  staff   256  8 30 10:25 ..\n-rw-r--r--  1 developer  staff  1024  8 30 10:30 package.json\ndrwxr-xr-x  3 developer  staff    96  8 30 10:28 src\ndrwxr-xr-x  4 developer  staff   128  8 30 10:29 dist', explanation: '列出当前目录的所有文件和文件夹，包括隐藏文件，以长格式显示详细信息', status: 'success', directory: '~/projects/ai-terminal' },
            { id: 2, sessionId: 'session_001', timestamp: '2023-08-30 10:25:42', command: 'git status', output: 'On branch main\nYour branch is up to date with \'origin/main\'.\n\nChanges not staged for commit:\n  (use "git add <file>..." to update what will be committed)\n  (use "git restore <file>..." to discard changes in working directory)\n\tmodified:   src/index.js\n\nno changes added to commit (use "git add" and/or "git commit -a")', explanation: '显示Git工作区和暂存区的状态，包括未跟踪、已修改和已暂存的文件', status: 'success', directory: '~/projects/ai-terminal' },
            { id: 3, sessionId: 'session_001', timestamp: '2023-08-30 10:20:30', command: 'npm run build', output: '> ai-terminal@1.0.0 build\n> webpack --mode production\n\nHash: a1b2c3d4e5f\nVersion: webpack 5.76.0\nTime: 2345ms\nBuilt at: 2023-08-30 10:35:45\n    Asset      Size  Chunks             Chunk Names\nbundle.js  1.23 MiB       0  [emitted]  main\nEntrypoint main = bundle.js', explanation: '执行构建脚本，将源代码编译打包成生产环境可用的文件', status: 'success', directory: '~/projects/ai-terminal' },
            { id: 4, sessionId: 'session_002', timestamp: '2023-08-30 10:15:22', command: 'git add .', output: '添加所有文件到暂存区', explanation: '将当前目录下所有修改的文件添加到Git暂存区', status: 'success', directory: '~/projects/ai-terminal' },
            { id: 5, sessionId: 'session_002', timestamp: '2023-08-30 10:10:18', command: 'git commit -m "Update README.md"', output: '[main 1a2b3c4] Update README.md\n 1 file changed, 15 insertions(+), 3 deletions(-)', explanation: 'Git版本控制命令，用于管理代码仓库', status: 'success', directory: '~/projects/ai-terminal' },
            { id: 6, sessionId: 'session_002', timestamp: '2023-08-30 10:05:45', command: 'npm install lodash', output: 'npm WARN ai-terminal@1.0.0 No description\nnpm WARN ai-terminal@1.0.0 No repository field.\n\n+ lodash@4.17.21\nadded 1 package from 2 contributors and audited 1 package in 2.345s\n\nfound 0 vulnerabilities', explanation: 'Node Package Manager命令，用于管理Node.js项目依赖', status: 'success', directory: '~/projects/ai-terminal' },
            { id: 7, sessionId: 'session_003', timestamp: '2023-08-30 10:00:33', command: 'docker-compose up -d', output: 'Creating network "ai-terminal_default" with the default driver\nCreating ai-terminal_web_1 ... done\nCreating ai-terminal_db_1  ... done', explanation: '启动docker-compose.yml中定义的所有服务', status: 'success', directory: '~/projects/ai-terminal' },
            { id: 8, sessionId: 'session_003', timestamp: '2023-08-30 09:55:20', command: 'git push origin main', output: 'Enumerating objects: 5, done.\nCounting objects: 100% (5/5), done.\nDelta compression using up to 8 threads\nCompressing objects: 100% (3/3), done.\nWriting objects: 100% (3/3), 345 bytes | 345.00 KiB/s, done.\nTotal 3 (delta 2), reused 0 (delta 0)\nTo github.com:user/ai-terminal.git\n   1a2b3c4..5e6f7g8  main -> main', explanation: 'Git版本控制命令，用于管理代码仓库', status: 'success', directory: '~/projects/ai-terminal' }
        ];
        
        // 分页相关变量
        let currentPage = 1;
        const itemsPerPage = 5;
        let filteredHistory = [...commandHistory];
        
        // 历史命令功能已整合到命令中心下拉菜单中
        
        // 搜索功能
        historySearch.addEventListener('input', () => {
            currentPage = 1;
            filterAndDisplayHistory();
        });
        
        // 分页功能
        prevPageBtn.addEventListener('click', () => {
            if (currentPage > 1) {
                currentPage--;
                filterAndDisplayHistory();
            }
        });
        
        nextPageBtn.addEventListener('click', () => {
            const totalPages = Math.ceil(filteredHistory.length / itemsPerPage);
            if (currentPage < totalPages) {
                currentPage++;
                filterAndDisplayHistory();
            }
        });
        
        // 过滤和显示历史命令
        function filterAndDisplayHistory() {
            const searchTerm = historySearch.value.toLowerCase();
            filteredHistory = commandHistory.filter(item => 
                item.command.toLowerCase().includes(searchTerm) || 
                (item.explanation && item.explanation.toLowerCase().includes(searchTerm))
            );
            
            // 更新分页信息
            const totalPages = Math.ceil(filteredHistory.length / itemsPerPage);
            pageInfo.textContent = `第 ${currentPage} 页，共 ${totalPages} 页`;
            
            // 更新分页按钮状态
            prevPageBtn.disabled = currentPage === 1;
            nextPageBtn.disabled = currentPage === totalPages || totalPages === 0;
            
            // 显示当前页的数据
            const startIndex = (currentPage - 1) * itemsPerPage;
            const endIndex = startIndex + itemsPerPage;
            const pageItems = filteredHistory.slice(startIndex, endIndex);
            
            // 清空表格
            historyTableBody.innerHTML = '';
            
            // 添加数据到表格
            pageItems.forEach(item => {
                const row = document.createElement('tr');
                
                // 时间列
                const timeCell = document.createElement('td');
                timeCell.textContent = item.timestamp;
                row.appendChild(timeCell);
                
                // 会话ID列
                const sessionCell = document.createElement('td');
                sessionCell.textContent = item.sessionId;
                row.appendChild(sessionCell);
                
                // 命令列
                const commandCell = document.createElement('td');
                commandCell.className = 'command-cell';
                commandCell.textContent = item.command;
                row.appendChild(commandCell);
                
                // 解释列
                const explanationCell = document.createElement('td');
                explanationCell.className = 'explanation-cell';
                if (item.explanation) {
                    explanationCell.innerHTML = `
                        <div class="explanation-content">
                            <span class="explanation-icon">💡</span>
                            <span class="explanation-text">${item.explanation}</span>
                        </div>
                    `;
                } else {
                    explanationCell.innerHTML = `
                        <span class="no-explanation">暂无解释</span>
                    `;
                }
                row.appendChild(explanationCell);
                
                // 操作列
                const actionsCell = document.createElement('td');
                actionsCell.className = 'history-actions';
                
                const runButton = document.createElement('button');
                runButton.textContent = '执行';
                runButton.addEventListener('click', () => {
                    executeCommand(item.command);
                    historyModal.style.display = 'none';
                });
                
                const explainButton = document.createElement('button');
                explainButton.textContent = '解释';
                explainButton.addEventListener('click', () => {
                    generateAIExplanation(item);
                });
                
                const outputButton = document.createElement('button');
                outputButton.textContent = '输出';
                outputButton.addEventListener('click', () => {
                    showCommandOutput(item);
                });
                
                const deleteButton = document.createElement('button');
                deleteButton.textContent = '删除';
                deleteButton.addEventListener('click', () => {
                    deleteHistoryItem(item.id);
                });
                
                actionsCell.appendChild(runButton);
                actionsCell.appendChild(explainButton);
                actionsCell.appendChild(outputButton);
                actionsCell.appendChild(deleteButton);
                row.appendChild(actionsCell);
                
                historyTableBody.appendChild(row);
            });
        }
        
        // 执行命令
        function executeCommand(command) {
            // 在终端中显示命令
            const commandLine = document.createElement('div');
            commandLine.className = 'command-line';
            commandLine.innerHTML = '<span class="prompt">developer@macbook</span><span>~/projects/ai-terminal $</span> ' + command;
            terminalContent.appendChild(commandLine);
            
            // 模拟命令执行结果
            let outputLine = document.createElement('div');
            outputLine.className = 'command-output';
            
            // 根据不同命令显示不同结果
            let outputText = '';
            if (command === 'ls -la') {
                outputText = 'total 24\ndrwxr-xr-x  5 developer  staff   160  8 30 10:30 .\ndrwxr-xr-x  8 developer  staff   256  8 30 10:25 ..\n-rw-r--r--  1 developer  staff  1024  8 30 10:30 package.json\ndrwxr-xr-x  3 developer  staff    96  8 30 10:28 src\ndrwxr-xr-x  4 developer  staff   128  8 30 10:29 dist';
            } else if (command === 'git status') {
                outputText = 'On branch main\nYour branch is up to date with \'origin/main\'.\n\nChanges not staged for commit:\n  (use "git add <file>..." to update what will be committed)\n  (use "git restore <file>..." to discard changes in working directory)\n\tmodified:   src/index.js\n\nno changes added to commit (use "git add" and/or "git commit -a")';
            } else if (command.startsWith('npm run')) {
                outputText = '> ai-terminal@1.0.0 ' + command + '\n> ' + command.replace('npm run ', '') + '\n\n正在执行任务...';
            } else {
                outputText = '命令已执行: ' + command;
            }
            
            outputLine.textContent = outputText;
            terminalContent.appendChild(outputLine);
            
            // 智能命令解释 - 只在需要时解释
            if (commandExplainEnabled && shouldExplainCommand(command)) {
                const explanation = getCommandExplanation(command);
                if (explanation) {
                    const explainContainer = document.createElement('div');
                    explainContainer.className = 'command-explanation-container';
                    explainContainer.innerHTML = `
                        <div class="explanation-header">
                            <span class="explanation-icon">💡</span>
                            <span class="explanation-text">${explanation}</span>
                            <button class="hide-explanation" onclick="this.parentElement.parentElement.style.display='none'">×</button>
                        </div>
                    `;
                    terminalContent.appendChild(explainContainer);
                }
            }
            
            // 如果启用了上下文感知，提供后续建议
            if (contextAwareEnabled) {
                const contextSuggestion = getContextSuggestion(command, outputText);
                if (contextSuggestion) {
                    setTimeout(() => {
                        showSmartSuggestion(contextSuggestion);
                    }, 500);
                }
            }
            
            // 滚动到底部
            terminalContent.scrollTop = terminalContent.scrollHeight;
            
            // 添加到历史记录
            const newHistoryItem = {
                id: commandHistory.length + 1,
                sessionId: 'session_001',
                timestamp: new Date().toLocaleString('zh-CN'),
                command: command,
                output: outputText,
                explanation: (commandExplainEnabled && shouldExplainCommand(command)) ? getCommandExplanation(command) : '',
                status: 'success',
                directory: '~/projects/ai-terminal'
            };
            
            commandHistory.unshift(newHistoryItem);
        }
        
        // 判断是否应该解释命令的智能函数
        function shouldExplainCommand(command) {
            // 简单常用命令不需要解释
            const simpleCommands = ['ls', 'cd', 'pwd', 'clear', 'exit', 'help'];
            if (simpleCommands.includes(command.trim())) {
                return false;
            }
            
            // 检查是否是复杂命令（带参数）
            const hasParameters = command.includes(' -') || command.includes(' --');
            
            // 检查用户是否是新手（基于命令历史）
            const isNoviceUser = commandHistory.length < 10;
            
            // 检查是否是首次使用该命令
            const isFirstTime = !commandHistory.some(item => item.command === command);
            
            // 检查是否是不常见的命令
            const uncommonCommands = ['docker', 'grep', 'awk', 'sed', 'find', 'git log', 'npm run'];
            const isUncommonCommand = uncommonCommands.some(cmd => command.startsWith(cmd));
            
            // 满足以下条件之一就解释：
            return hasParameters || isNoviceUser || isFirstTime || isUncommonCommand;
        }
        
        // 获取命令解释
        function getCommandExplanation(command) {
            const explanations = {
                'ls -la': '列出当前目录的所有文件和文件夹，包括隐藏文件，以长格式显示详细信息',
                'git status': '显示Git工作区和暂存区的状态，包括未跟踪、已修改和已暂存的文件',
                'npm run dev': '执行package.json中定义的dev脚本，通常用于启动开发服务器',
                'npm run build': '执行构建脚本，将源代码编译打包成生产环境可用的文件',
                'docker ps': '显示当前正在运行的Docker容器列表',
                'git log --oneline': '以简洁的单行格式显示Git提交历史',
                'docker-compose up': '启动docker-compose.yml中定义的所有服务'
            };
            
            // 精确匹配
            if (explanations[command]) {
                return explanations[command];
            }
            
            // 模糊匹配常见命令模式
            if (command.startsWith('git ')) {
                return 'Git版本控制命令，用于管理代码仓库';
            } else if (command.startsWith('npm ')) {
                return 'Node Package Manager命令，用于管理Node.js项目依赖';
            } else if (command.startsWith('docker ')) {
                return 'Docker容器管理命令，用于容器化应用的部署和管理';
            }
            
            return null;
        }
        
        // 获取上下文建议
        function getContextSuggestion(command, output) {
            if (command === 'git status' && output.includes('modified')) {
                return '检测到有文件修改，建议执行 git add . 然后 git commit 提交更改';
            } else if (command === 'ls -la' && output.includes('package.json')) {
                return '检测到Node.js项目，可以尝试运行 npm install 或 npm run dev';
            } else if (command.startsWith('npm run') && output.includes('正在执行')) {
                return '任务正在后台运行，可以打开浏览器查看结果或查看日志';
            } else if (command === 'docker ps' && !output.includes('CONTAINER')) {
                return '当前没有运行的容器，可以使用 docker-compose up 启动服务';
            }
            
            return null;
        }
        
        // 删除历史记录项
        function deleteHistoryItem(id) {
            if (confirm('确定要删除这条历史记录吗？')) {
                // 从历史记录数组中删除该项
                commandHistory = commandHistory.filter(item => item.id !== id);
                
                // 重新显示历史记录
                filterAndDisplayHistory();
            }
        }
        
        // 显示命令输出
        function showCommandOutput(item) {
            // 设置弹窗内容
            outputCommand.textContent = item.command;
            outputTimestamp.textContent = item.timestamp;
            outputContent.textContent = item.output || '暂无输出内容';
            
            // 显示弹窗
            outputModal.style.display = 'flex';
        }
        
        // 生成AI解释
        function generateAIExplanation(item) {
            // 模拟AI生成解释
            const explanations = {
                'git status': '检查Git仓库状态，显示工作区和暂存区的文件变更情况',
                'ls -la': '列出当前目录下的所有文件和文件夹，包括隐藏文件，以详细列表格式显示',
                'npm run build': '执行项目构建脚本，将源代码打包成生产环境可用的文件',
                'git add .': '将当前目录下所有文件的变更添加到暂存区',
                'git commit -m "Update README.md"': '将暂存区的变更提交到本地仓库，并添加提交信息',
                'npm install lodash': '安装lodash库到项目依赖中',
                'docker-compose up -d': '以后台模式启动docker-compose定义的服务',
                'git push origin main': '将本地main分支的提交推送到远程仓库'
            };
            
            // 更新历史记录中的解释
            const historyItem = commandHistory.find(h => h.id === item.id);
            if (historyItem) {
                historyItem.explanation = explanations[item.command] || '这是"' + item.command + '"命令的解释说明。';
                
                // 更新表格显示
                filterAndDisplayHistory();
                
                // 在智能建议区域显示AI解释
                const aiSuggestion = document.createElement('div');
                aiSuggestion.className = 'ai-suggestion';
                aiSuggestion.innerHTML = '<strong>AI解释:</strong> ' + historyItem.explanation;
                
                // 查找智能建议区域
                const smartSuggestions = document.querySelector('.smart-suggestions');
                if (smartSuggestions) {
                    // 清空现有内容并添加新的AI解释
                    smartSuggestions.innerHTML = '';
                    smartSuggestions.appendChild(aiSuggestion);
                }
            }
        }
        
        // AI面板相关元素
        const aiPanel = document.getElementById('aiPanel');
        const closeAiPanel = document.getElementById('closeAiPanel');
        const aiChatInput = document.getElementById('aiChatInput');
        const sendChatBtn = document.getElementById('sendChatBtn');
        const aiChatMessages = document.getElementById('aiChatMessages');
        const modelSelector = document.getElementById('modelSelector');
        const modelStatus = document.getElementById('modelStatus');
        
        // AI功能状态
        let contextAwareEnabled = true;
        let commandExplainEnabled = true;
        let isAiPanelOpen = false;
        let currentModel = 'gpt-4';
        
        // AI助手按钮功能 - 打开右侧面板
        aiButton.addEventListener('click', () => {
            toggleAiPanel();
        });
        
        // 关闭AI面板按钮
        closeAiPanel.addEventListener('click', () => {
            toggleAiPanel();
        });
        
        // 切换AI面板显示
        function toggleAiPanel() {
            isAiPanelOpen = !isAiPanelOpen;
            
            if (isAiPanelOpen) {
                aiPanel.style.display = 'flex';
                aiButton.innerHTML = '🤖 AI聊天';
                aiButton.style.backgroundColor = '#005a9e';
            } else {
                aiPanel.style.display = 'none';
                aiButton.innerHTML = '🤖 AI助手';
                aiButton.style.backgroundColor = '#3c3c3c';
            }
        }
        
        // 从localStorage加载设置
        function loadSettings() {
            const settings = localStorage.getItem('aiTerminalSettings');
            if (settings) {
                const parsed = JSON.parse(settings);
                contextAwareEnabled = parsed.contextAware !== undefined ? parsed.contextAware : true;
                commandExplainEnabled = parsed.commandExplain !== undefined ? parsed.commandExplain : true;
            }
        }
        
        // 保存设置到localStorage
        function saveSettings() {
            const settings = {
                contextAware: contextAwareEnabled,
                commandExplain: commandExplainEnabled
            };
            localStorage.setItem('aiTerminalSettings', JSON.stringify(settings));
        }
        
        // 初始化时加载设置
        loadSettings();
        
        // 设置面板中的AI功能切换
        const contextAwareSetting = document.getElementById('contextAwareSetting');
        const commandExplainSetting = document.getElementById('commandExplainSetting');
        
        // 同步设置状态到UI
        function syncSettingsToUI() {
            contextAwareSetting.checked = contextAwareEnabled;
            commandExplainSetting.checked = commandExplainEnabled;
        }
        
        // 初始化设置状态
        syncSettingsToUI();
        
        // 上下文感知功能切换
        contextAwareSetting.addEventListener('change', () => {
            contextAwareEnabled = contextAwareSetting.checked;
            saveSettings();
            console.log('🧠 上下文感知已', contextAwareEnabled ? '启用' : '禁用');
        });
        
        // 命令解释功能切换  
        commandExplainSetting.addEventListener('change', () => {
            commandExplainEnabled = commandExplainSetting.checked;
            saveSettings();
            console.log('💡 命令解释已', commandExplainEnabled ? '启用' : '禁用');
        });
        
        // 显示智能建议
        function showSmartSuggestion(message) {
            // 这个函数现在用于显示简单的状态信息
            console.log('[AI建议]', message);
        }

        // 初始化建议项点击事件
        function initSuggestionClicks() {
            const suggestionItems = document.querySelectorAll('.suggestion-item.clickable');
            suggestionItems.forEach(item => {
                item.addEventListener('click', () => {
                    const command = item.getAttribute('data-cmd');
                    if (command) {
                        executeCommand(command);
                        // 执行后更新建议（这里可以添加更复杂的逻辑）
                        updateContextSuggestions(command);
                    }
                });
            });
        }

        // 折叠/展开建议区域功能
        function initToggleSuggestions() {
            const toggleButton = document.getElementById('toggleSuggestions');
            const suggestionsContent = document.getElementById('suggestionsContent');
            
            toggleButton.addEventListener('click', () => {
                suggestionsContent.classList.toggle('collapsed');
                toggleButton.textContent = suggestionsContent.classList.contains('collapsed') ? '︾' : '︽';
            });
        }

        // 点击终端区域自动隐藏建议区域功能
        function initAutoHideSuggestions() {
            const terminalContent = document.querySelector('.terminal-content');
            const suggestionsContent = document.getElementById('suggestionsContent');
            const toggleButton = document.getElementById('toggleSuggestions');
            
            terminalContent.addEventListener('click', (event) => {
                // 检查点击的元素是否在建议区域内
                if (!event.target.closest('.context-suggestions')) {
                    // 如果建议区域是展开的，则折叠它
                    if (!suggestionsContent.classList.contains('collapsed')) {
                        suggestionsContent.classList.add('collapsed');
                        toggleButton.textContent = '︾';
                    }
                }
            });
        }

        // 更新上下文建议（示例）
        function updateContextSuggestions(lastCommand) {
            const sequence = document.querySelector('.command-sequence');
            const suggestions = document.querySelector('.suggestion-items');
            
            // 这里可以根据最新命令更新建议
            // 示例：添加新的命令到序列
            console.log('更新建议基于命令:', lastCommand);
        }

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', () => {
            initSuggestionClicks();
            initToggleSuggestions();
            initAutoHideSuggestions();
        });
        
        // 发送消息功能
        function sendMessage() {
            const messageText = aiChatInput.value.trim();
            if (!messageText) return;
            
            // 添加用户消息
            addUserMessage(messageText);
            aiChatInput.value = '';
            
            // 模拟AI回复（延迟一点时间）
            setTimeout(() => {
                const aiResponse = generateAIResponse(messageText);
                addAIMessage(aiResponse);
            }, 1000);
        }
        
        // 添加用户消息
        function addUserMessage(text) {
            const messageDiv = document.createElement('div');
            messageDiv.className = 'user-message';
            messageDiv.innerHTML = `
                <div class="message-avatar">👤</div>
                <div class="message-content">
                    <div class="message-text">${text}</div>
                    <div class="message-time">${getCurrentTime()}</div>
                </div>
            `;
            aiChatMessages.appendChild(messageDiv);
            scrollChatToBottom();
        }
        
        // 添加AI消息 (支持结构化响应)
        function addAIMessage(response) {
            const messageDiv = document.createElement('div');
            messageDiv.className = 'ai-message';
            
            // 处理字符串响应（向后兼容）
            if (typeof response === 'string') {
                messageDiv.innerHTML = `
                    <div class="message-avatar">🤖</div>
                    <div class="message-content">
                        <div class="message-text">${response}</div>
                        <div class="message-time">${getCurrentTime()}</div>
                    </div>
                `;
            } else {
                // 处理结构化响应
                const { message, commands } = response;
                let commandBlocksHtml = '';
                
                if (commands && commands.length > 0) {
                    commandBlocksHtml = '<div class="command-blocks">';
                    commands.forEach((cmd, index) => {
                        commandBlocksHtml += `
                            <div class="command-block">
                                <div class="command-header">
                                    <div class="command-text">${cmd.command}</div>
                                    <button class="command-run-btn" onclick="runCommand('${cmd.command.replace(/'/g, "\\'")}')">运行</button>
                                </div>
                                ${cmd.explain ? `<div class="command-explain">${cmd.explain}</div>` : ''}
                            </div>
                        `;
                    });
                    commandBlocksHtml += '</div>';
                }
                
                messageDiv.innerHTML = `
                    <div class="message-avatar">🤖</div>
                    <div class="message-content">
                        <div class="message-text">${message || ''}</div>
                        ${commandBlocksHtml}
                        <div class="message-time">${getCurrentTime()}</div>
                    </div>
                `;
            }
            
            aiChatMessages.appendChild(messageDiv);
            scrollChatToBottom();
        }
        
        // 生成AI回复（支持命令建议）
        function generateAIResponse(userMessage) {
            const lowerMessage = userMessage.toLowerCase();
            
            if (lowerMessage.includes('git') && (lowerMessage.includes('提交') || lowerMessage.includes('commit'))) {
                return {
                    message: '我来帮你完成Git提交流程。通常需要以下几个步骤：',
                    commands: [
                        { command: 'git status', explain: '查看当前仓库状态，了解有哪些文件被修改' },
                        { command: 'git add .', explain: '将所有修改的文件添加到暂存区' },
                        { command: 'git commit -m "your commit message"', explain: '提交更改，记得修改提交信息' }
                    ]
                };
            } else if (lowerMessage.includes('npm') && (lowerMessage.includes('项目') || lowerMessage.includes('开始'))) {
                return {
                    message: '开始一个新的Node.js项目，我建议按以下步骤操作：',
                    commands: [
                        { command: 'npm init -y', explain: '快速初始化package.json文件' },
                        { command: 'npm install express', explain: '安装Express框架作为示例依赖' },
                        { command: 'npm run dev', explain: '启动开发服务器' }
                    ]
                };
            } else if (lowerMessage.includes('docker') && (lowerMessage.includes('启动') || lowerMessage.includes('运行'))) {
                return {
                    message: 'Docker容器管理，这些命令可以帮你快速上手：',
                    commands: [
                        { command: 'docker ps', explain: '查看当前运行的容器' },
                        { command: 'docker images', explain: '列出所有可用的镜像' },
                        { command: 'docker-compose up -d', explain: '后台启动所有服务' }
                    ]
                };
            } else if (lowerMessage.includes('git') && lowerMessage.includes('分支')) {
                return {
                    message: 'Git分支操作的常用命令：',
                    commands: [
                        { command: 'git branch', explain: '查看所有本地分支' },
                        { command: 'git checkout -b new-feature', explain: '创建并切换到新分支' },
                        { command: 'git merge main', explain: '合并main分支的更改' }
                    ]
                };
            } else if (lowerMessage.includes('git')) {
                return {
                    message: '关于Git命令，这里是一些基础操作：',
                    commands: [
                        { command: 'git status', explain: '查看仓库当前状态' },
                        { command: 'git log --oneline', explain: '查看提交历史（简洁版）' }
                    ]
                };
            } else if (lowerMessage.includes('npm') || lowerMessage.includes('node')) {
                return {
                    message: 'Node.js和npm的常用命令：',
                    commands: [
                        { command: 'npm install', explain: '安装package.json中的所有依赖' },
                        { command: 'npm run build', explain: '构建项目' }
                    ]
                };
            } else if (lowerMessage.includes('ls') || lowerMessage.includes('文件')) {
                return {
                    message: '文件和目录操作的基本命令：',
                    commands: [
                        { command: 'ls -la', explain: '详细列出所有文件（包括隐藏文件）' },
                        { command: 'pwd', explain: '显示当前目录路径' }
                    ]
                };
            } else {
                return {
                    message: `我理解你想了解"${userMessage}"相关的内容。我可以为你提供具体的命令建议。试试问我关于Git、Node.js、Docker等具体操作吧！`
                };
            }
        }
        
        // 从聊天中运行命令
        function runCommand(command) {
            // 执行命令到终端
            executeCommand(command);
            
            // 添加系统消息到AI聊天中
            const systemMessage = document.createElement('div');
            systemMessage.className = 'system-message';
            systemMessage.innerHTML = `
                <div class="system-content">
                    <div class="system-text">已执行命令: ${command}</div>
                </div>
            `;
            aiChatMessages.appendChild(systemMessage);
            scrollChatToBottom();
        }
        
        // 获取当前时间
        function getCurrentTime() {
            return new Date().toLocaleTimeString('zh-CN', { 
                hour: '2-digit', 
                minute: '2-digit' 
            });
        }
        
        // 滚动聊天到底部
        function scrollChatToBottom() {
            aiChatMessages.scrollTop = aiChatMessages.scrollHeight;
        }
        
        // 发送按钮事件
        sendChatBtn.addEventListener('click', sendMessage);
        
        // 输入框回车事件
        aiChatInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                sendMessage();
            }
        });
        
        // 模型选择事件
        modelSelector.addEventListener('change', (e) => {
            currentModel = e.target.value;
            updateModelStatus();
            
            // 在聊天中显示模型切换信息
            addSystemMessage(`已切换到模型: ${e.target.options[e.target.selectedIndex].text}`);
        });
        
        // 更新模型状态显示
        function updateModelStatus() {
            const statusIndicator = modelStatus.querySelector('.status-indicator');
            const statusText = modelStatus.querySelector('.status-text');
            
            // 模拟不同模型的连接状态
            const modelStates = {
                'gpt-4': { status: 'connected', text: '已连接' },
                'claude-3': { status: 'disconnected', text: '未配置' },
                'local-llm': { status: 'connected', text: '本地运行' }
            };
            
            const state = modelStates[currentModel] || { status: 'disconnected', text: '未知状态' };
            
            statusIndicator.className = `status-indicator ${state.status}`;
            statusText.textContent = state.text;
        }
        
        // 添加系统消息
        function addSystemMessage(text) {
            const messageDiv = document.createElement('div');
            messageDiv.className = 'system-message';
            messageDiv.innerHTML = `
                <div class="system-content">
                    <div class="system-text">ℹ️ ${text}</div>
                    <div class="message-time">${getCurrentTime()}</div>
                </div>
            `;
            aiChatMessages.appendChild(messageDiv);
            scrollChatToBottom();
        }
        
        // AI模型配置相关元素
        const modelsListSection = document.getElementById('modelsListSection');
        const modelFormSection = document.getElementById('modelFormSection');
        const addModelBtn = document.getElementById('addModelBtn');
        const backToListBtn = document.getElementById('backToListBtn');
        const testConfigBtn = document.getElementById('testConfigBtn');
        const modelForm = document.getElementById('modelForm');
        const testResult = document.getElementById('testResult');
        
        // 设置按钮功能
        settingsButton.addEventListener('click', () => {
            settingsModal.style.display = 'flex';
            showModelsList();
        });
        
        // 关闭设置弹窗
        closeSettingsModal.addEventListener('click', () => {
            settingsModal.style.display = 'none';
        });
        
        // 显示模型列表
        function showModelsList() {
            modelsListSection.style.display = 'block';
            modelFormSection.style.display = 'none';
        }
        
        // 显示添加/编辑表单
        function showModelForm(isEdit = false, modelData = null) {
            modelsListSection.style.display = 'none';
            modelFormSection.style.display = 'block';
            
            const formTitle = document.getElementById('formTitle');
            formTitle.textContent = isEdit ? '编辑模型' : '添加新模型';
            
            if (isEdit && modelData) {
                // 填充表单数据
                document.getElementById('modelDisplayName').value = modelData.displayName;
                document.getElementById('modelName').value = modelData.modelName;
                document.getElementById('apiUrl').value = modelData.apiUrl;
                document.getElementById('apiKey').value = modelData.apiKey;
            } else {
                // 清空表单
                modelForm.reset();
            }
            
            testResult.style.display = 'none';
        }
        
        // 添加模型按钮
        addModelBtn.addEventListener('click', () => {
            showModelForm(false);
        });
        
        // 返回列表按钮
        backToListBtn.addEventListener('click', () => {
            showModelsList();
        });
        
        // 取消按钮
        document.getElementById('cancelFormBtn').addEventListener('click', () => {
            showModelsList();
        });
        
        // 测试连接按钮
        testConfigBtn.addEventListener('click', () => {
            const apiUrl = document.getElementById('apiUrl').value;
            const apiKey = document.getElementById('apiKey').value;
            const modelName = document.getElementById('modelName').value;
            
            if (!apiUrl || !apiKey || !modelName) {
                showTestResult(false, '请填写完整的配置信息');
                return;
            }
            
            // 模拟测试连接
            testConfigBtn.textContent = '🔄 测试中...';
            testConfigBtn.disabled = true;
            
            setTimeout(() => {
                const isSuccess = Math.random() > 0.3; // 70%成功率模拟
                if (isSuccess) {
                    showTestResult(true, '连接成功！模型可以正常使用');
                } else {
                    showTestResult(false, '连接失败：API Key无效或网络错误');
                }
                
                testConfigBtn.textContent = '🔍 测试连接';
                testConfigBtn.disabled = false;
            }, 2000);
        });
        
        // 显示测试结果
        function showTestResult(success, message) {
            testResult.style.display = 'block';
            testResult.className = 'test-result ' + (success ? 'success' : 'error');
            testResult.textContent = message;
        }
        
        // 保存模型配置
        modelForm.addEventListener('submit', (e) => {
            e.preventDefault();
            
            const displayName = document.getElementById('modelDisplayName').value;
            const modelName = document.getElementById('modelName').value;
            const apiUrl = document.getElementById('apiUrl').value;
            const apiKey = document.getElementById('apiKey').value;
            
            // 模拟保存
            console.log('保存模型配置:', {displayName, modelName, apiUrl, apiKey: '***'});
            
            // 检查是否已存在该模型选项
            const existingOption = Array.from(modelSelector.options).find(opt => opt.value === modelName);
            if (!existingOption) {
                // 添加新的模型选项
                const option = document.createElement('option');
                option.value = modelName;
                option.textContent = displayName;
                modelSelector.appendChild(option);
                
                // 自动选择新添加的模型
                modelSelector.value = modelName;
                currentModel = modelName;
                updateModelStatus();
            }
            
            showModelsList();
            alert('模型配置已保存！');
        });
    </script>
</body>
</html>